
package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.CoordinateConvert;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKOLUpdateElement;
import com.baidu.mapapi.MKOfflineMap;
import com.baidu.mapapi.MKOfflineMapListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.MapFieldVO;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.overlays.StadiumOverlay;
import com.zhu.salesmanagement.overlays.StadiumOverlayItem;

public class MyLocationActivity extends MapActivity implements LocationListener , View.OnClickListener{
    public final static int MAP_ZOOM_LEVEL = 15 ;

    private BMapManager mapManager;
    private MyLocationOverlay myLocationOverlay;
    private MapView mapView;
    private MapController mapController;
    private ImageView myPlaceView = null;
    private Location myLocation = null;
    private MKOfflineMap mOffline = null;
    private VisitTaskInfo mMapFieldVO = null;
    private View mPopView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_map);
        mapManager = SalesApplication.mApplicaton.getMapManager();
        if (mapManager == null) {
            Log.e("zhu","mapManager is null");
            mapManager = new BMapManager(getApplication());
            mapManager.init(SalesApplication.mStrKey, new SalesApplication.MyGeneralListener());
        }
        //mapManager.start();

        mMapFieldVO = new VisitTaskInfo();
		mMapFieldVO.mLatitude = getIntent().getDoubleExtra("lat", 31.2367);
		mMapFieldVO.mLongitude = getIntent().getDoubleExtra("lng", 121.50107);
		mMapFieldVO.mName = getIntent().getStringExtra("name");
		mMapFieldVO.mAddress = getIntent().getStringExtra("addr");

        super.initMapActivity(mapManager);
        setupViews();
    }

    private void setupViews() {
    	findViewById(R.id.left_button).setOnClickListener(this);
    	findViewById(R.id.myplaceImage).setVisibility(View.GONE);
    	//findViewById(R.id.myplaceImage).setOnClickListener(this);

        mapView = (MapView) findViewById(R.id.map_view);
        mapView.setTraffic(false);
        mapView.setSatellite(false);
        mapView.setBuiltInZoomControls(true);
        GeoPoint point = new GeoPoint((int) (mMapFieldVO.mLatitude * 1E6), (int) (mMapFieldVO.mLongitude * 1E6));
        mapController = mapView.getController();
        mapController.setCenter(point);
        mapController.setZoom(MAP_ZOOM_LEVEL);
        //myLocationOverlay = new MyLocationOverlay(this, mapView);
        //myLocationOverlay.enableMyLocation();
        //myLocationOverlay.enableCompass();
        //mapView.getOverlays().add(myLocationOverlay);

        mOffline = new MKOfflineMap();
        mOffline.init(mapManager, new MKOfflineMapListener() {
            @Override
            public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                    case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                    {
                    MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                    // mText.setText(String.format("%s : %d%%", update.cityName,
                    // update.ratio));
                }
                    break;
                case MKOfflineMap.TYPE_NEW_OFFLINE:
                    Log.d("zhu", String.format("add offlinemap num:%d", state));
                    break;
                case MKOfflineMap.TYPE_VER_UPDATE:
                    Log.d("zhu", String.format("new offlinemap ver"));
                    break;
            }
        }
        });
        int num = mOffline.scan();
        if(Actions.DEBUG){
            Log.e("zhu","num="+num);
        }

        mPopView=super.getLayoutInflater().inflate(R.layout.overlay_pop, null);
        mapView.addView(mPopView, new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,  
    	        MapView.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER));
        mPopView.setVisibility(View.GONE);

		addOverlays();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    protected void onDestroy() {
        /*if (mapManager != null) {
            mapManager.destroy();
            mapManager = null;
        }*/
        mOffline = null;
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        if (mapManager != null) {
            //mapManager.getLocationManager().removeUpdates(this);
            mapManager.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mapManager != null) {
            //mapManager.getLocationManager().enableProvider(MKLocationManager.MK_GPS_PROVIDER);
            //mapManager.getLocationManager().enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
            //mapManager.getLocationManager().requestLocationUpdates(this);
            mapManager.start();
        }
        super.onResume();
    }

    @Override
    protected boolean isLocationDisplayed() {
        return myLocationOverlay.isMyLocationEnabled();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            myLocation = location;
//            final GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1e6),
//                    (int) (location.getLongitude() * 1e6));
//            mapController.setCenter(pt);
        }
    }

    private void goMyplace(){
        if(myLocation != null){
            GeoPoint currentGeo = new GeoPoint((int) (myLocation.getLatitude() * 1e6),(int) (myLocation.getLongitude() * 1e6));
            mapController.animateTo(currentGeo);
        }
    }

    private void addOverlays() {
		List<Overlay> overlays = this.mapView.getOverlays();
		Drawable stadiumDrawable = getResources().getDrawable(R.drawable.db_r);
		StadiumOverlay stadiumOverlay = new StadiumOverlay(stadiumDrawable,
				this, null, null);

		if (mMapFieldVO != null) {
			StadiumOverlayItem item = new StadiumOverlayItem(mMapFieldVO);
			stadiumOverlay.addOverlay(item);
		}
		stadiumOverlay.setOnFocusChangeListener(onPopChangeListener);
		overlays.add(stadiumOverlay);
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v != null){
			switch(v.getId()){
				case R.id.myplaceImage:
					goMyplace();
					break;
				case R.id.left_button:
					finish();
					break;
			}
		}
	}

//    private String getTextTmp(){
//        String tem = "";
//        if(myLocation != null){
//            tem += "默认：" +myLocation.getLatitude() + ","+ myLocation.getLongitude();
//            GeoPoint geoPt = convertToBaidu09Coord(new GeoPoint((int)(myLocation.getLatitude() *1e6),(int)(myLocation.getLongitude() *1e6)) , MKLocationManager.MK_COORDINATE_WGS84);
//            tem += "\nWGS84：" +geoPt.getLatitudeE6() + ","+ geoPt.getLongitudeE6();
//        }
//        return tem;
//    }
//
//    public static GeoPoint convertToBaidu09Coord(GeoPoint geoPt, int coordType) {
//        GeoPoint retGeoPt;
//        Bundle bundle;
//        switch (coordType) {
//            case MKLocationManager.MK_COORDINATE_WGS84:
//                bundle = CoordinateConvert.fromWgs84ToBaidu(geoPt);
//                retGeoPt = CoordinateConvert.bundleDecode(bundle);
//                break;
//            case MKLocationManager.MK_COORDINATE_GCJ:
//                bundle = CoordinateConvert.fromGcjToBaidu(geoPt);
//                retGeoPt = CoordinateConvert.bundleDecode(bundle);
//                break;
//            case MKLocationManager.MK_COORDINATE_BAIDU09:
//            default:
//                retGeoPt = geoPt;
//                break;
//        }
//        return retGeoPt;
//    }

	private final ItemizedOverlay.OnFocusChangeListener onPopChangeListener = new ItemizedOverlay.OnFocusChangeListener() {  
        public void onFocusChanged(ItemizedOverlay overlay, OverlayItem newFocus) {  
            if (mPopView != null) {  
            	mPopView.setVisibility(View.GONE);  
            }  
            if (newFocus != null) {  
            	
            	MyLocationActivity.this.mapController.animateTo(newFocus.getPoint());
            	
                MapView.LayoutParams geoLP = (MapView.LayoutParams) mPopView.getLayoutParams();  
                geoLP.point = newFocus.getPoint();
                
                LinearLayout popView_layout = (LinearLayout) mPopView.findViewById(R.id.popview_layout);
                popView_layout.setOnClickListener(popViewClickListener);
                TextView title = (TextView) mPopView.findViewById(R.id.overlay_field_title_txt);  
                title.setText(newFocus.getTitle());  
                
                
                TextView desc = (TextView) mPopView.findViewById(R.id.overlay_field_disc_txt);
                if (newFocus.getSnippet() == null || newFocus.getSnippet().length() == 0) {  
                    desc.setVisibility(View.GONE);  
                } else {  
                    desc.setVisibility(View.VISIBLE);  
                    desc.setText(newFocus.getSnippet());  
                }  
                mapView.updateViewLayout(mPopView, geoLP);  
                mPopView.setVisibility(View.VISIBLE);  
            }  
        }  
    };

    private OnClickListener popViewClickListener = new OnClickListener() {
		public void onClick(View v) {

		}
	};
}
